package com.sgb.kjwl.view.ui.fragment.self.company

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentManagementDynamicBinding
import com.sgb.kjwl.databinding.ItemManageDynamicBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.self.ManagementDynamicEntity
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity
import com.sgb.kjwl.view.widget.manage.GradientBgTextView
import com.sgb.kjwl.viewmodel.self.company.ManagementDynamicViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import javax.inject.Inject

class ManagementDynamicFragment : AppLazyFragment(){

    @Inject
    lateinit var mViewModel : ManagementDynamicViewModel
    private var mType : String = ""
    private var mName : String = ""

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mBinding : FragmentManagementDynamicBinding

    private lateinit var mAdapter : DynamicAdapter

    companion object{
        const val TAG = "managementDynamicFragment"
        const val KEY_TYPE = "key_type"
        const val KEY_NAME = "key_name"
        fun newInstance(type : String, name : String)  : ManagementDynamicFragment {
            val fragment = ManagementDynamicFragment()
            val bundle = Bundle()
            bundle.putString(KEY_TYPE, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null){
            mType = requireArguments().getString(KEY_TYPE, "")
            mName = requireArguments().getString(KEY_NAME, "")
        }
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_management_dynamic, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                mBinding.refreshLayout.finishLoadMore(500)
                mViewModel.getManagementDynamicList(context!!, mType, isLoadMore)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                mViewModel.getManagementDynamicList(context!!, mType, isLoadMore)
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = DynamicAdapter(requireContext(), R.layout.item_manage_dynamic)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setCallBack(object : DynamicAdapter.ClickCallback{
            override fun clickName(item: ManagementDynamicEntity) {
                //去网站
                if (!TextUtils.isEmpty(item.userCompanyNo)){
                    WebsiteInfoActivity.start(context, item.userCompanyNo, WebsiteInfoActivity.WEBSITE_FOR_COMPANY)
                } else if (!TextUtils.isEmpty(item.userNo)) {
                    WebsiteInfoActivity.start(context, item.userNo, WebsiteInfoActivity.WEBSITE_FOR_PERSONAL)
                }
            }

            override fun clickContent(item: ManagementDynamicEntity) {
                if (!TextUtils.isEmpty(item.key)) {
                    WebViewX5HostActivity.start(context, item.key)
                }
            }

        })
        mViewModel.mManagementDynamicList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (mName == "资产"){
                mAdapter.setIsAssets(true)
            } else {
                mAdapter.setIsAssets(false)
            }
            if (isLoadMore){
                mAdapter.addData(it)
            } else {
                mBinding.recycleView.scrollToPosition(0)
                mAdapter.setNewData(it)
            }
        })
    }

    override fun onLazyLoad() {
        isLoadMore = false
        mViewModel.getManagementDynamicList(requireContext(), mType, isLoadMore)
    }


    class DynamicAdapter (context: Context, layoutId : Int) : BaseQuickAdapter<ManagementDynamicEntity, BaseViewHolder>(layoutId){

        private var mCallback : ClickCallback ?= null
        private var mIsAssets = false
        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(context.resources.getColor(R.color.color_secondary_blue))

        fun setCallBack(callback : ClickCallback){
            this.mCallback = callback
        }
        fun setIsAssets(isAssets  : Boolean){
            this.mIsAssets = isAssets
        }

        private var mItemBinding : ItemManageDynamicBinding?= null
        override fun convert(helper: BaseViewHolder?, item: ManagementDynamicEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                mItemBinding!!.executePendingBindings()
                if (item!!.type == "13"){
                    mItemBinding!!.tvContent.text = "关注了我"
                } else {
                    mItemBinding!!.tvContent.text = "查看了【" + item.businessName + "】"
                    //setColorSpan("查看了【" + item.businessName + "】", mItemBinding!!.tvContent)
                }

                mItemBinding!!.tvType.setColors(R.color.transparent, R.color.transparent)
                setType(item, mItemBinding!!.tvType)
//                mItemBinding!!.tvName.setOnClickListener {
//                      if (mCallback != null){
//                          mCallback!!.clickName(item)
//                      }
//                }
//                mItemBinding!!.tvContent.setOnClickListener {
//                    if (mCallback != null){
//                        mCallback!!.clickContent(item)
//                    }
//                }
                mItemBinding!!.root.setOnClickListener {
                    if (mCallback != null){
                        mCallback!!.clickName(item)
                    }
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            val ssb = SpannableStringBuilder(content)
            ssb.setSpan(mColorSpan, content.indexOf("【"), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

        //设置类型
        @SuppressLint("UseCompatLoadingForDrawables")
        private fun setType(item: ManagementDynamicEntity?, tvType: GradientBgTextView) {
            when(item!!.type){
                "1" -> {//商品
                    tvType.text = "商品"
                    tvType.setColors(R.color.color_gradient, R.color.color_main)
                }
                "2" -> {//货运
                    tvType.text = "货运"
                    tvType.setColors(R.color.color_secondary_green_third, R.color.color_third_green_easy)
                }
                "3" -> {//网站
                    tvType.text = "网站"
                    tvType.setColors(R.color.color_secondary_purple_four, R.color.color_secondary_purple_third)
                }
                "4"-> {//商标转让
                    tvType.text = "商标转让"
                    tvType.setColors(R.color.color_secondary_yellow_four, R.color.color_secondary_yellow_third)
                }
                "5"-> {//版权转让
                    tvType.text = "版权转让"
                    tvType.setColors(R.color.color_secondary_yellow_four, R.color.color_secondary_yellow_third)
                }
                "6"-> {//专利转让
                    tvType.text = "专利转让"
                    tvType.setColors(R.color.color_secondary_yellow_four, R.color.color_secondary_yellow_third)
                }
                "7"-> {//公司转让
                    tvType.text = "公司转让"
                    tvType.setColors(R.color.color_secondary_yellow_four, R.color.color_secondary_yellow_third)
                }
                "8"-> {//资产转让
                    if (mIsAssets){
                        tvType.text = "资产"
                        tvType.setColors(
                            R.color.color_secondary_orange_six,
                            R.color.color_secondary_orange_fifth
                        )
                    } else {
                        tvType.text = "资产转让"
                        tvType.setColors(
                            R.color.color_secondary_yellow_four,
                            R.color.color_secondary_yellow_third
                        )
                    }
                }
                "9"-> {//服务
                    tvType.text = "服务"
                    tvType.setColors(R.color.color_secondary_orange_four, R.color.color_secondary_orange_third, )
                }
                "10"-> {//需求
                    tvType.text = "需求"
                    tvType.setColors(R.color.color_secondary_green_easy_third, R.color.color_secondary_green_easy)
                }
                "11"-> {//招聘
                    tvType.text = "招聘"
                    tvType.setColors(R.color.color_secondary_blue_four, R.color.color_secondary_blue_third)
                }
                "12"-> {//团队
                    tvType.text = "团队"
                    tvType.setColors(R.color.color_secondary_blue_six, R.color.color_secondary_blue_fifth, )
                }
                "13" -> {//关注
                    tvType.text = "关注"
                    tvType.setColors(R.color.color_secondary_blue_third, R.color.color_secondary_blue_four)
                }
            }
        }


        interface ClickCallback {
            fun clickName(item: ManagementDynamicEntity)
            fun clickContent(item: ManagementDynamicEntity)
        }

    }
}